<?php
/**
 * Created by PhpStorm.
 * User: Lxx<779219930@qq.com>
 * Date: 2016/4/20
 * Time: 15:34
 */

namespace app\home\controller;
use app\home\model\Summary;
use app\home\model\Test;
use app\home\model\WechatUser;
use com\wechat\TPWechat;
use app\home\model\ZsbOaStFw;
use app\home\model\Xuexiao;
use app\home\model\OaStudent;
use app\home\model\ZsbOaStudent;
use app\home\model\OaStFw;
use app\admin\model\Sign;
use app\home\model\Teacher;
use think\Config;
use think\Db;
/**
 * Class User
 * 用户个人中心
 */
class User extends Base {
    /**
     * 个人中心主页
     */
    public function index(){
        $userId = session('userId');
        $user = WechatUser::where('openid',$userId)->field('openid,subscribe,review_status,role,name,nickname,score,headimgurl')->find();
        //总榜
        $I = Db::query('SELECT COUNT(*) AS sum FROM pb_wechat_user WHERE subscribe = 1 AND review_status = 1 AND score >'.$user['score']);
        $user['rankk'] = $I[0]['sum'];
        $user['name'] = $user['name'] ? $user['name'] : $user['nickname'];
        $this->assign('user',$user);
        return $this->fetch();
    }
    /**
     * 个人信息页
     */
    public function personal(){
        $userId = input('openid',session('userId'));
        $user = WechatUser::where('openid',$userId)->find();
        switch ($user['sex']) {
            case 0:
                $user['sex'] = "未定义";
                break;
            case 1:
                $user['sex'] = "男";
                break;
            case 2:
                $user['sex'] = "女";
                break;
            default:
                break;
        }
        if ($user['words']){
            $arr = [];
            foreach (json_decode($user['words']) as $value){
                switch ($value){
                    case 1:
                        array_push($arr,['id' => 1,'name' => '考研']);
                        break;
                    case 2:
                        array_push($arr,['id' => 2,'name' => '专升本']);
                        break;
                    case 3:
                        array_push($arr,['id' => 3,'name' => '四六级']);
                        break;
                    case 4:
                        array_push($arr,['id' => 4,'name' => '雅思']);
                        break;
                    case 5:
                        array_push($arr,['id' => 5,'name' => '托福']);
                        break;
                    default:
                        array_push($arr,['id' => 0,'name' => '暂无']);
                }
            }
            $this->assign('words',$arr);
        }
        $this->assign('user',$user);
        return $this->fetch();
    }
    /*
     * 单词
     */
    public function play(){
        $id = input('id'); // 账号
        $tp = WechatUser::where('openid',$id)->value('type');
        $type = input('type');
        $res = WechatUser::where(['openid' => $id])->update(['type' => $type]);
        if ($res){
            $result = Db::name('word_sign')->where(['openid' => $id,'type' => $tp])->find();
            if (!empty($result)){
                Db::name('word_sign')->where(['openid' => $id,'type' => $tp])->delete();
            }
            return $this->success('操作成功');
        }else{
            return $this->error('操作失败');
        }
    }
    /*联系方式*/
    public function call(){
        $userId = input('openid',session('userId'));
        $user = WechatUser::where('openid',$userId)->find();
        if ($user['subscribe'] == 0 || $user['review_status'] == 0){
            $this->redirect('Journal/null');
        }
        $list = Db::name('xxbteacher')->where(['name' => ['neq','']])->order('id','asc')->select();
        $this->assign('list',$list);
        return $this->fetch();
    }
    /**
     * 认证页面
     */
    public function register(){
        $userId = input('openid',session('userId'));
        $user = WechatUser::where('openid',$userId)->field('subscribe,school_id,role,review_status,name,tel,vip_id,order_id')->find();
        if ($user['subscribe'] == 0){
            $this->redirect('Journal/null');
        }
        if (IS_POST){
            $tel = input('post.tel');
            $type = input('post.type');
            $tels = WechatUser::where('tel',$tel)->find();
            if ($tels){
                return ['code' => 0 ,'msg' => '抱歉~该手机号已被认证！请联系您的服务老师'];
            }
            $vip_id = '';
            $order_id = '';
            if ($type == 1){
                // 专升本
                $res = ZsbOaStudent::where('tel',$tel)->find();
                if ($res){
                    $school = $res['dx_id']; // 学校
                    $name = $res['name']; // 名字
                    $time = $res['nf'];  //考研年份
                    $ress = ZsbOaStFw::where('s_id',$res['id'])->find();
                    $flag = false;
                    if ($ress){
                        if($time <= 2019){
                            $order_id = 'z'.substr($ress['order_id'],-8);
                        }else{
                            $order_id = 'z'.substr($ress['order_id'],-9);
                        }
                        $flag = true;
                    }
                }else{
                    // 手机号错误 联系老师
                    return ['code' => 0 ,'msg' => '抱歉~认证失败！暂无您的学员记录，请仔细确认手机号码'];
                }
            }else{
                // 其他学员
                $res = OaStudent::where('tel',$tel)->find();
                if ($res){
                    $school = $res['dx_id']; // 学校
                    $name = $res['name']; // 名字
                    $time = $res['nf'];  //考研年份
                    $ress = OaStFw::where('s_id',$res['id'])->find();
                    $flag = false;
                    if ($ress){
                        $arr = OaStFw::where('s_id',$res['id'])->column('order_id');
                        $temp = '';
                        foreach($arr as $value){
                            if (substr($value,0,2) == 'dd' && substr($temp,0,2) != 'dd'){
                                // 考研
                                $temp = $value;
                            }elseif (substr($value,0,2) == 'jj' || substr($value,0,2) == 'ce' || substr($value,0,2) == 'sy' || substr($value,0,2) == 'tf' || substr($value,0,2) == 'ky'){
                                // 计算机 j 四六级  雅思 托福  口译 y
                                if (substr($temp,0,2) != 'dd' && substr($temp,0,2) != 'jj'){
                                    $temp = $value;
                                }
                            }elseif (substr($value,0,2) == 'lx'){
                                // 留学 l
                                if (substr($temp,0,2) != 'dd' && substr($temp,0,2) != 'jj' && substr($temp,0,2) == 'ce' && substr($temp,0,2) != 'sy' && substr($temp,0,2) != 'tf' && substr($temp,0,2) != 'ky'){
                                    $temp = $value;
                                }
                            }
                        }
                        if (substr($temp,0,2) == 'dd'){
                            // 考研
                            $order_id = 'k'.substr($temp,-9);
                        }elseif (substr($temp,0,2) == 'jj'){
                            // 计算机
                            $order_id = 'j'.substr($temp,-9);
                        }elseif (substr($temp,0,2) == 'ce' || substr($temp,0,2) == 'sy' || substr($temp,0,2) == 'tf' || substr($temp,0,2) == 'ky'){
                            // 英语 y
                            $order_id = 'y'.substr($temp,-9);
                        }elseif (substr($temp,0,2) == 'lx'){
                            // 留学 l
                            $order_id = 'l'.substr($temp,-9);
                        }
                        $vip_id = $ress['vip_id'];
                        $flag = true;
                    }
                }else{
                    // 手机号错误 联系老师
                    return ['code' => 0 ,'msg' => '抱歉~认证失败！暂无您的学员记录，请仔细确认手机号码'];
                }
            }
            if ($flag){
                $data = array(
                    'name' => iconv("gbk", "utf-8//ignore", $name),
                    'school_id'=> $school,
                    'party' => $time,
                    'order_id' => $order_id,
                    'vip_id' => $vip_id,
                    'tel' => $tel,
                    'review_status' => 1,
                );
                WechatUser::where('openid',$userId)->update($data);
                $Wechat = new TPWechat(Config::get('party'));
                $send = array(
                    "touser" => $userId,
                    "msgtype" => "text",
                    "text" => ['content' => '恭喜~~ 【 '.$data["name"].' 】 认证成功！']
                );
                $Wechat->sendCustomMessage($send);
                return ['code' => 1 ,'msg' => '恭喜~认证成功！'];
            }else{
                // 无服务
                return ['code' => 2 ,'msg' => '抱歉~认证失败！您非VIP服务学员，请联系您的服务老师','data' => ''];
            }
        }else{
            $user['xuexiao'] = '暂无';
            if ($user['school_id']){
                if (false === strpos($user['school_id'],',')){
                    // 学生
                    $user['xuexiao'] = get_school($user['school_id']);
                }else{
                    $arr = array();
                    foreach (explode(',',$user['school_id']) as $value){
                        array_push($arr,get_school($value));
                    }
                    $user['xuexiao'] = implode('，',$arr);
                }
            }
            $user['position'] = '暂无';
            if ($user['role'] == 1){
                // 老师
                $user['position'] = !empty(Teacher::where('tel',$user['tel'])->value('zhiwei')) ? Teacher::where('tel',$user['tel'])->value('zhiwei') : '暂无';
            }
            $this->assign('msg',$user);
            return $this->fetch();
        }
    }
    /**
     * 老师认证
     */
    public function teacher(){
        $userId = session('userId');
        $user = WechatUser::where('openid',$userId)->find();
        if ($user['subscribe'] == 0){
            $this->redirect('Journal/null');
        }
        if ($user['review_status'] == 1){
            $this->redirect('User/register');
        }
        if (IS_POST){
            $tel = input('post.tel');
            $tels = WechatUser::where('tel',$tel)->find();
            if ($tels){
                return ['code' => 0 ,'msg' => '抱歉~该手机号已被认证！请重试。'];
            }
            $res = Teacher::where('tel',$tel)->find();
            if ($res){
                $data = array(
                    'name' => $res['name'],
                    'tel' => $tel,
                    'school_id' => $res['dx'],
                    'review_status' => 1,
                    'role' => 1
                );
                WechatUser::where('openid',$userId)->update($data);
                $Wechat = new TPWechat(Config::get('party'));
                $send = array(
                    "touser" => $userId,
                    "msgtype" => "text",
                    "text" => ['content' => '恭喜~~ 【 '.$data["name"].'老师 】 认证成功！']
                );
                $Wechat->sendCustomMessage($send);
                return ['code' => 1 ,'msg' => '恭喜~认证成功！'];
            }else{
                // 手机号错误 联系老师
                return ['code' => 0 ,'msg' => '抱歉~认证失败！暂无您的记录，请仔细确认手机号码'];
            }
        }else{
            return $this->fetch();
        }
    }
    /**
     * 我的签到
     */
    public function sign(){
        $userId = input('openid',session('userId'));
        $User = WechatUser::where(['openid' => $userId])->field('subscribe,review_status,role')->find();
        if ($User['review_status'] == 0 || $User['subscribe'] == 0 || $User['role'] == 1){
            $this->redirect('Journal/null');
        }
        $year = input('year', date('Y'));
        $month = input('month', date('m'));
        $res = array('yes' => [],'no' => []);
        if(strtotime($year.'-'.$month) > strtotime(date("Y-m"))){
            return json_encode($res);
        }
        $month_first = mktime(0,0,0,$month,1,$year);
        $month_final = mktime(23,59,59,$month,date('t',strtotime(date($year.'-'.$month))),$year);
        for ($start = $month_first;$start <= $month_final;$start += 24 * 3600){
            $first = strtotime(date('Y-m-d 00:00:00',$start));
            $end = strtotime(date('Y-m-d 23:59:59',$start));
            $tem = Sign::where(['openid' => $userId ,"create_time" =>['between',[$first,$end]]])->find();
            if (date('Ymd',$start) <= date('Ymd')){
                if ($tem){
                    // 签到
                    $res['yes'][] = intval(date('j',$start));
                }else{
                    // 未签到
                    $res['no'][] = intval(date('j',$start));
                }
            }
        }
        if(IS_POST) {
            return json_encode($res);
        }else{
            $this->assign('openid',$userId);
            $this->assign('yes',json_encode($res['yes']));
            $this->assign('no',json_encode($res['no']));
            return $this->fetch();
        }
    }
    /**
     *  学员管理
     */
    public function see(){
        $userId = input('openid', session('userId'));
        $User = WechatUser::where(['openid' => $userId])->field('subscribe,review_status,role,school_id')->find();
        if ($User['review_status'] == 0 || $User['role'] == 0 || $User['subscribe'] == 0){
            $this->redirect('Journal/null');
        }
        // 获取所在学校
        $arr = array();
        if ($User['school_id']){
            foreach (explode(',',$User['school_id']) as $key => $value){
                $school = Xuexiao::where('dx_id',$value)->find();
                if ($school){
                    $arr[$key]['id'] = $value;
                    $arr[$key]['name'] = iconv("gbk", "utf-8//ignore", $school['dx']);
                }
            }
            $d_name = $arr[0]['name'];
            $d_id = $arr[0]['id'];
        }else{
            $d_name = '暂无';
            $d_id = 0;
        }
        $year = date('Y');
        $Year = [];
        while (count($Year) <= 4){
            $Year[] = $year;
            $year += 1;
        }
        array_push($Year,'所有');
        $this->assign('now','所有');
        $this->assign('arr',$Year);
        $this->assign('d_name',$d_name);
        $this->assign('deps',$arr);
        $this->assign('id',$d_id);
        return $this ->fetch();
    }
    /**
     * 学校筛选
     */
    public function select(){
        $id = input('id');
        $year = input('year');  // 年份  时间/所有
        if ($year == "所有"){
            $map = ['review_status' => 1,'role' => 0 ,'school_id' => $id];
        }else{
            $map = ['review_status' => 1,'role' => 0 ,'school_id' => $id,'party' => $year];
        }
        $list = WechatUser::where($map)->order('order_id')->limit(20)->field('openid,percent,percents,name,order_id,headimgurl,order_id')->select();  // 获取 用户列表
        $now = strtotime(date('Y-m-d 09:00:00')); // 当天九点
        $before = $now - 86400; // 前一天
        foreach ($list as $value){
            $Sign = Sign::where(['openid' => $value['openid']])->whereTime('create_time','d')->value('openid');
            $value['is_sign'] = 0;
            $value['is_summary'] = 0;
            $value['is_test'] = 0;
            $value['is_homework'] = 0;
            $value['is_translate'] = 0;
            if ($Sign){
                // 未签到
                $value['is_sign'] = 1;
            }
            $Summary = Summary::where(['openid' => $value['openid'],'create_time' => ['between',[$before,$now]]])->value('openid');
            if ($Summary){
                // 未提交总结
                $value['is_summary'] = 1;
            }
            $Test = Test::where(['openid' => $value['openid']])->whereTime('create_time','d')->value('openid');
            if ($Test){
                // 未提交测试
                $value['is_test'] = 1;
            }
            $Homework = \app\home\model\Homework::where(['openid' => $value['openid'],'create_time' => ['between',[$before,$now]]])->value('openid');
            if ($Homework){
                $value['is_homework'] = 1;
            }
            $Translate = Db::name('translate_answer')->where(['openid' => $value['openid'],'create_time' => ['between',[strtotime(date('Y-m-d')),time()]]])->value('openid');
            if ($Translate){
                $value['is_translate'] = 1;
            }
        }
        if ($list){
            return ['code' => 1,'data' => $list];
        }else{
            return ['code' => 0,'data' => ''];
        }
    }
    /**
     * 搜索
     */
    public function search(){
        $userId = input('openid', session('userId'));
        $User = WechatUser::where(['openid' => $userId])->field('subscribe,review_status,role,school_id')->find();
        if ($User['review_status'] == 0 || $User['role'] == 0 || $User['subscribe'] == 0){
            $this->redirect('Journal/null');
        }
        if (IS_POST){
            $id = input('id');
            $search = input('search');
            $map = ['review_status' => 1,'role' => 0 ,'school_id' => $id,'name' => ['like', "%$search%"]];
            $list = WechatUser::where($map)->order('order_id')->select();  // 获取 用户列表
            $now = strtotime(date('Y-m-d 09:00:00')); // 当天九点
            $before = $now - 86400; // 前一天
            foreach ($list as $value){
                $Sign = Sign::where(['openid' => $value['openid']])->whereTime('create_time','d')->find();
                $value['is_sign'] = 0;
                $value['is_summary'] = 0;
                $value['is_test'] = 0;
                $value['is_homework'] = 0;
                if ($Sign){
                    // 未签到
                    $value['is_sign'] = 1;
                }
                $Summary = Summary::where(['openid' => $value['openid'],'create_time' => ['between',[$before,$now]]])->find();
                if ($Summary){
                    // 未提交总结
                    $value['is_summary'] = 1;
                }
                $Test = Test::where(['openid' => $value['openid']])->whereTime('create_time','d')->find();
                if ($Test){
                    // 未提交测试
                    $value['is_test'] = 1;
                }
                $Homework = \app\home\model\Homework::where(['openid' => $value['openid'],'create_time' => ['between',[$before,$now]]])->find();
                if ($Homework){
                    $value['is_homework'] = 1;
                }
            }
            if ($list){
                return ['code' => 1,'data' => $list];
            }else{
                return ['code' => 0,'data' => ''];
            }
        }else{
            $id = input('id');
            $this->assign('id',$id);
            return $this->fetch();
        }
    }
    /**
     * 学员管理 加载更多
     */
    public function more(){
        $len = input('length/d');
        $id = input('id/d');
        $year = input('year');
        if ($year == "所有"){
            $map = ['review_status' => 1,'role' => 0 ,'school_id' => $id];
        }else{
            $map = ['review_status' => 1,'role' => 0 ,'school_id' => $id,'party' => $year];
        }
        $list = WechatUser::where($map)->order('order_id')->limit($len,20)->field('openid,percent,percents,name,order_id,headimgurl')->select();  // 获取 用户列表
        $now = strtotime(date('Y-m-d 09:00:00')); // 当天九点
        $before = $now - 86400; // 前一天
        foreach ($list as $value){
            $Sign = Sign::where(['openid' => $value['openid']])->whereTime('create_time','d')->value('openid');
            $value['is_sign'] = 0;
            $value['is_summary'] = 0;
            $value['is_test'] = 0;
            if ($Sign){
                // 未签到
                $value['is_sign'] = 1;
            }
            $Summary = Summary::where(['openid' => $value['openid'],'create_time' => ['between',[$before,$now]]])->value('openid');
            if ($Summary){
                // 未提交总结
                $value['is_summary'] = 1;
            }
            $Test = Test::where(['openid' => $value['openid']])->whereTime('create_time','d')->value('openid');
            if ($Test){
                // 未提交测试
                $value['is_test'] = 1;
            }
            $Homework = \app\home\model\Homework::where(['openid' => $value['openid'],'create_time' => ['between',[$before,$now]]])->value('openid');
            if ($Homework){
                $value['is_homework'] = 1;
            }
        }
        if ($list){
            return ['code' => 1,'data' => $list];
        }else{
            return ['code' => 0,'data' => ''];
        }
    }
    /**
     * 统计详情
     */
    public function detail(){
        $userId = session('userId');
        $User = WechatUser::where(['openid' => $userId])->field('subscribe,review_status,role,school_id')->find();
        if ($User['review_status'] == 0 || $User['role'] == 0 || $User['subscribe'] == 0){
            $this->redirect('Journal/null');
        }
        $id = input('id');
        if (empty($id)){
            $this->redirect('Journal/del');
        }
        $years = date('Y');
        $Year = [];
        while (count($Year) <= 5){
            $Year[] = $years;
            $years += 1;
        }
        $this->assign('years',$Year);
        $this->assign('y',date('Y'));
        $this->assign('id',$id);
        return $this->fetch();
    }
    /**
     * 年份筛选
     */
    public function details(){
        $id = input('id');
        $year = input('year');
        $now = strtotime(date('Y-m-d 09:00:00')); // 当天九点
        $before = $now - 86400; // 前一天
        $map = ['review_status' => 1,'role' => 0 ,'school_id' => $id,'party' => $year];
        $list = WechatUser::where($map)->order('order_id')->field('openid,headimgurl,order_id,name')->select();  // 获取 用户列表
        $arr1= array(); // 签到
        $arr2 = array(); // 总结
        $arr3 = array();  // 测试
        $arr4 = array();  //作业
        foreach ($list as $value){
            $Sign = Sign::where(['openid' => $value['openid']])->whereTime('create_time','d')->value('openid');
            if (empty($Sign)){
                // 未签到
                array_push($arr1,['name' => $value['name'],'head' => $value['headimgurl'],'vip' =>$value['order_id']?$value['order_id']:'*空*']);
            }
            $Summary = Summary::where(['openid' => $value['openid'],'create_time' => ['between',[$before,$now]]])->value('openid');
            if (empty($Summary)){
                // 未提交总结
                array_push($arr2,['name' => $value['name'],'head' => $value['headimgurl'],'vip' =>$value['order_id']?$value['order_id']:'*空*']);
            }
            $Test = Test::where(['openid' => $value['openid']])->whereTime('create_time','d')->value('openid');
            if (empty($Test)){
                // 未提交测试
                array_push($arr3,['name' => $value['name'],'head' => $value['headimgurl'],'vip' =>$value['order_id']?$value['order_id']:'*空*']);
            }
            $Homework = \app\home\model\Homework::where(['openid' => $value['openid'],'create_time' => ['between',[$before,$now]]])->value('openid');
            if (empty($Homework)){
                // 为提交作业
                array_push($arr4,['name' => $value['name'],'head' => $value['headimgurl'],'vip' =>$value['order_id']?$value['order_id']:'*空*']);
            }
        }
        return $this->success('加载成功','',['sign' => $arr1,'summary' => $arr2,'test' => $arr3,'homework' => $arr4,'list' => count($list)]);
    }
}
